# ===============开发调试使用的代码================
import os, sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'meiduo_mall.settings.dev')
sys.path.insert(0, '/home/python/Desktop/sz37_meiduo_mall/meiduo_mall')

# 导入django
import django
django.setup()
# ===============开发调试使用的代码================


from django.template import loader
from django.conf import settings
from copy import deepcopy
# import os

from goods.models import GoodsCategory, GoodsChannel, SKU, SpecificationOption
from goods.models import GoodsSpecification, SKUSpecification


def get_breadcrumb(category):
    dict = {
        'cat1': '',
        'cat2': '',
        'cat3': '',
    }

    if category.parent is None:
        dict['cat1'] = category.name
    elif category.parent.parent is None:
        dict['cat2'] = category.name
        dict['cat1'] = category.parent.name
    else:
        dict['cat3'] = category.name
        dict['cat2'] = category.parent.name
        dict['cat1'] = category.parent.parent.name

    return dict


def get_categories():
    # =======频道分组===========
    categories = {}
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    for channel in channels:
        if channel.group_id not in categories:
            categories[channel.group_id] = {
                'channels': [],
                'sub_cats': []
            }

        # 一级分类
        # cat1s = GoodsChannel.objects.filter(group_id=channel.group_id)
        cat1 = channel.category

        categories[channel.group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })

        # 二级分类
        cat2s = GoodsCategory.objects.filter(parent_id=cat1.id)
        for cat2 in cat2s:
            # 三级分类
            cat3s = GoodsCategory.objects.filter(parent_id=cat2.id)
            cat3s_list = []
            for cat3 in cat3s:
                cat3s_list.append({
                    'id': cat3.id,
                    'name': cat3.name
                })
            categories[channel.group_id]['sub_cats'].append({
                'id': cat2.id,
                'name': cat2.name,
                'sub_cats': cat3s_list
            })

    return categories


def get_goods_and_specs(sku_id):
    # =========3\获取动态数据的封装==============
    # 3.1
    sku = SKU.objects.get(id=sku_id)

    # 3.3-记录当前sku的选项组合
    cur_sku_spec_options = SKUSpecification.objects.filter(sku=sku).order_by('spec_id')
    cur_sku_options = []  # [1, 4, 7]
    for temp in cur_sku_spec_options:
        cur_sku_options.append(temp.option_id)

    # 3.1-GOODS即SPU的对象,通过外键属性获取对象goods
    goods = sku.goods

    # 3.4 罗列出和当前sku同类的所有商品的选项和商品id的映射关系
    # {(1,4,7):1, (1,3,7):2}
    sku_options_mapping = {}
    skus = SKU.objects.filter(goods=goods)
    for temp_sku in skus:
        sku_spec_options = SKUSpecification.objects.filter(sku=temp_sku).order_by('spec_id')
        sku_options = []
        for temp in sku_spec_options:
            sku_options.append(temp.option_id)  # [1,4,7]
        sku_options_mapping[tuple(sku_options)] = temp_sku.id  # {(1,4,7):1}

    # 3.1
    specs = GoodsSpecification.objects.filter(goods=goods).order_by('id')

    # 3.2
    for index, spec in enumerate(specs):
        # 3.2
        options = SpecificationOption.objects.filter(spec=spec)

        # 3.5
        temp_list = deepcopy(cur_sku_options)
        for option in options:
            temp_list[index] = option.id
            option.sku_id = sku_options_mapping.get(tuple(temp_list))
        # 在每个规格对象中动态添加一个属性spec_options来记录当前规格有哪些选项
        spec.spec_options = options

    return goods, sku, specs


# # 放到异步方案里边
# def generate_static_sku_detail_html(sku_id):
#
#     # =========2\获取动态数据==============
#     categories = get_categories()
#
#     # 代码有些多可以使用封装函数进行调用
#     # sku = SKU.objects.get(id=sku_id)
#     # # GOODS即SPU的对象,通过外键属性获取对象
#     # goods = sku.goods
#     # specs = None
#
#     goods, sku, specs = get_goods_and_specs(sku_id)
#
#     # ============1\先构建模板================
#     # 构建模板参数
#     context = {
#         'categories': categories,   # 先调试可以使用None
#         'goods': goods,
#         'sku': sku,
#         'specs': specs
#     }
#     # 获取模板
#     template = loader.get_template('detail.html')
#     # 渲染模板
#     sku_html_text = template.render(context=context)
#     # 写入模板
#     file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'goods/'
#                              + str(sku_id) + '.html')
#
#     with open(file_path, 'w', encoding='utf-8') as f:
#         f.write(sku_html_text)


# if __name__ == '__main__':
#     for num in range(1,17):
#         generate_static_sku_detail_html(num)




